<!doctype html>
<html>

	<head>
		<meta charset="utf-8">
		<title></title>
		<meta name="viewport"
			content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<link href="../css/mui.css" rel="stylesheet" />
		<link rel="stylesheet" href="../css/exhaust.css">
		<link rel="stylesheet" href="../css/icons.css">
	</head>

	<body>
		<header class="mui-bar mui-bar-nav">
			<h1 class="mui-title">智能排风</h1>
		</header>
		<!-- Main Content -->
		<main class="main-content">
			<div style="background-color: white">
				<button id="search" type="button" class="mui-btn mui-btn-outlined mui-btn-block">
					<span class="mui-icon mui-icon-search" style="color: #10B246;"></span>
					<span style="color: #969696;">请选择大棚</span>
				</button>
			</div>
			<!-- Header Info -->
			<section class="mb-6">
				<div id="today" class="text-2xl font-bold text-primary mb-2"></div>
				<div class="info-card">
					<div class="info-item">
						<span class="icon icon-leaf text-secondary mr-2"></span>
						<span id="name" class="font-medium" style="width: 90%;"></span>
					</div>
					<div class="info-item">
						<span class="icon icon-leaf text-secondary mr-2"></span>
						<span id="corps" class="font-medium" style="width: 90%;">当前作物:</span>
					</div>
					<div class="info-item">
						<span class="icon icon-map-marker text-secondary mr-2"></span>
						<span id="location" class="font-medium" style="width: 90%;">地理位置:</span>
					</div>
					<div class="info-item">
						<span class="icon icon-cloud-sun text-secondary mr-2"></span>
						<span id="weather" class="font-medium" style="width: 90%;">今日天气:</span>
					</div>
				</div>
			</section>

			<!-- Analysis Report -->
			<section class="mb-6">
				<div class="analysis-card">
					<h3 class="text-lg font-bold text-primary mb-2">今日排风计划分析</h3>
					<p id="reason" class="text-gray-700">

					</p>
				</div>
			</section>

			<!-- Today's Plan -->
			<section class="mb-6">
				<h3 class="text-lg font-bold text-primary mb-3">今日排风计划表</h3>
				<div class="table-container">
					<table>
						<thead>
							<tr>
								<th class="py-2 px-3 text-left">序号</th>
								<th class="py-2 px-3 text-left">开启时间</th>
								<th class="py-2 px-3 text-left">关闭时间</th>
								<th class="py-2 px-3 text-left">排风时长</th>
							</tr>
						</thead>
						<tbody id="scheduleDetail">

						</tbody>
					</table>
				</div>
			</section>

			<!-- History Plans -->
			<section>
				<h3 class="text-lg font-bold text-primary mb-3">历史排风计划</h3>
				<div class="history-list">
					<div id="history" class="divide-y"></div>
					<button id="showMoreHistory" class="btn" style="width:100%;margin:0.5rem 0;display:none;">查看更多</button>
				</div>
			</section>
		</main>

		<!-- History Detail Modal -->
		<div id="historyModal" class="modal">
			<div class="modal-content">
				<div class="modal-header">
					<h3 id="modalDate" class="text-lg font-bold"></h3>
					<div id="modalWeather" class="text-sm"></div>
				</div>
				<div class="modal-body">
					<h4 class="font-bold text-primary mb-3">排风计划详情</h4>
					<div id="modalSchedule" class="mb-4">
						
					</div>
					<div id="modalCreateTime" class="text-sm text-gray-500 mb-2"></div>
					<div id="modalCrops" class="text-sm text-gray-500"></div>
				</div>
				<div class="modal-footer">
					<button onclick="closeModal()" class="btn">关闭</button>
				</div>
			</div>
		</div>
		<script src="../js/mui.js"></script>
		<script src="../js/storage.js"></script>
		<script src="../js/request.js"></script>
		<script src="../js/date.js"></script>
		<script type="text/javascript">
			//测试使用
			// let greenhouseId = 3
			let greenhouseId = localStorage.getItem("greenhouseId")
			let greenhouseList = [];
			let greenhouse = {};
			let latestSchedule = {};
			let historyScheduleList = [];
			let today = parseTime(new Date(), '{y}-{m}-{d}');
			// let todayStr = parseTime(new Date(), '{y}年{m}月{d}日');

			mui.init()

			window.addEventListener('refresh', function(event) {
				document.getElementById("today").innerText = today;
				loadGreenhouseList();
				refresh();
			});
			
			function refresh(){
				if(!greenhouseId){
					return
				}
				getGreenhouseInfo();
				getTodaySchedule();
				getHistorySchedule();
			}
			
			mui("body").on("tap", "#search", function(event) {
				plus.nativeUI.actionSheet({
					title: "选择大棚", //这里就是这个弹窗的title
					cancel: "取消", //取消按钮
					buttons: greenhouseList,
				}, function(bt) {
					console.log('选项',bt.index)
					/*actionSheet 按钮点击事件*/
					if (bt.index > 0) {
						greenhouseId = greenhouseList[bt.index - 1].greenhouseId;
						refresh();
					}
				})
			})
			//显示大棚信息	
			function displayGreenhouseInfo() {
				document.getElementById("name").innerText = greenhouse.name;
				document.getElementById("corps").innerText = '当前作物：' + greenhouse.crop;
				document.getElementById("location").innerText = '地理位置：' + greenhouse.location;
			}
			//显示今天排风计划
			function displayTodaySchedule() {
				let table = document.getElementById('scheduleDetail');
				table.innerHTML = '';
				document.getElementById("weather").innerText = '今日天气：' + latestSchedule.weather;
				document.getElementById("reason").innerText = latestSchedule.reason;
				let scheduleDetail = latestSchedule.schedule ? JSON.parse(latestSchedule.schedule) : [];
				console.log('解析返回计划', JSON.stringify(scheduleDetail))
				let list = scheduleDetail.scheduleDetails;
				for (let i = 0; i < list.length; i++) {
					let item = list[i];
					let start = parseTime(item.startTime, '{h}:{i}');
					let end = parseTime(item.endTime, '{h}:{i}');
					let tr = document.createElement('tr');
					let row = `
						<td class="py-3 px-3">${i+1}</td>
						<td class="py-3 px-3">${start}</td>
						<td class="py-3 px-3">${end}</td>
						<td class="py-3 px-3">${item.duration}分钟</td>
					`;
					tr.innerHTML = row;
					table.append(tr);
				}
			}
			//显示历史排风计划
			function displayHistorySchedule(showAll = false) {
				let list = document.getElementById('history');
				list.innerHTML = '';
				let data = showAll ? historyScheduleList : historyScheduleList.slice(0, 5);
				data.forEach(schedule => {
					let date = parseTime(schedule.createTime, '{y}年{m}月{d}日');
					let div = document.createElement('div');
					div.className = 'history-item';
					div.addEventListener('tap', function(event) {
						displayScheduleModal(schedule.id);
					});
					let child = `
						<div class="history-item-content">
						    <div class="history-date">${date}</div>
						    <div class="history-summary">
						        <span class="history-weather">${schedule.weather || '暂无天气'}</span>
						        <span class="history-crop">${schedule.crop || '暂无作物'}</span>
						    </div>
						</div>
						<span class="icon icon-chevron-right text-gray-400"></span>
					`
					div.innerHTML = child;
					list.append(div);
				});
				// 控制查看更多按钮显示
				const showMoreBtn = document.getElementById('showMoreHistory');
				if (!showAll && historyScheduleList.length > 5) {
					showMoreBtn.style.display = '';
				} else {
					showMoreBtn.style.display = 'none';
				}
			}
			//显示弹出计划详情
			function displayScheduleModal(id) {
				let detail = historyScheduleList.find(schedule => schedule.id == id);
				showHistoryDetail(detail);
			}

			function showHistoryDetail(schedule) {
				let date = parseTime(schedule.createTime, '{y}年{m}月{d}日');
				document.getElementById('modalDate').textContent = date;
				document.getElementById('historyModal').style.display = 'flex';
				document.getElementById('modalWeather').innerText = '天气: ' + schedule.weather;
				document.getElementById('modalCreateTime').innerText = '计划生成时间: ' + schedule.createTime;
				document.getElementById('modalCrops').innerText = '作物: ' + greenhouse.crop;
				let modalSchedule = document.getElementById('modalSchedule')
				modalSchedule.innerHTML = '';
				let scheduleDetail = schedule.schedule ? JSON.parse(schedule.schedule) : [];
				console.log('解析返回计划', JSON.stringify(scheduleDetail))
				let list = scheduleDetail.scheduleDetails;
				for (let i = 0; i < list.length; i++) {
					let item = list[i];
					let start = parseTime(item.startTime, '{h}:{i}');
					let end = parseTime(item.endTime, '{h}:{i}');
					let div = document.createElement('div');
					div.className = 'flex justify-between mb-2';
					let row = `
						<span class="text-gray-600">${start} - ${end}</span>
						<span class="font-medium">${item.duration}分钟</span>
					`;
					div.innerHTML = row;
					modalSchedule.append(div);
				}
			}

			function closeModal() {
				document.getElementById('historyModal').style.display = 'none';
			}
			
			//获取大棚列表
			function loadGreenhouseList() {
				greenhouseList = [];
				let data = {}
				request.get('/system/greenhouse/list', data, (data) => {
					//提交成功回调
					console.log('调用服务端获取大棚信息成功');
					let list = data.rows;
					list.forEach(row => {
						let id = row.id;
						let name = row.name;
						greenhouseList.push({
							greenhouseId: id,
							title: name,
						})
					});
				}, (error, thrown) => {
					//发生错误时，回调
					console.error('调用服务端获取大棚信息失败', error);
				})
			}

			// 获取大棚信息
			function getGreenhouseInfo() {
				request.get('/system/greenhouse/' + greenhouseId, null, (data) => {
					//提交成功回调
					greenhouse = data.data;
					console.log('调用服务端获取大棚信息成功', JSON.stringify(greenhouse));
					displayGreenhouseInfo();
				}, (error, thrown) => {
					//发生错误时，回调
					console.error('调用服务端获取大棚信息失败', error);
				});
			}
			
			

			// 获取今天最新的排风计划
			function getTodaySchedule() {
				let data = {
					"greenhouseId": greenhouseId,
					"pageNum": 1,
					"pageSize": 1,
					"params": {
						"beginCreateTime": today + ' 00:00:00',
						"endCreateTime": today + ' 23:59:59',
					},
					"orderByColumn": "create_time",
					"isAsc": "desc",
				}

				request.get('/system/exhaustSchedule/list', data, (data) => {
					console.log('调用服务端获取今天最新的排风计划成功');
					//提交成功回调
					let list = data.rows;
					if (list.length > 0) {
						latestSchedule = list[0];
						console.log('今天最新排风计划', JSON.stringify(latestSchedule));
						displayTodaySchedule();
					}

				}, (error, thrown) => {
					//发生错误时，回调
					console.error('调用服务端获取今天最新的排风计划失败', error);
				})
			}

			// 获取历史排风计划
			function getHistorySchedule() {
				let data = {
					"greenhouseId": greenhouseId,
					"pageNum": 1,
					"pageSize": 10,
					"orderByColumn": "create_time",
					"isAsc": "desc",
				}

				request.get('/system/exhaustSchedule/list', data, (data) => {
					console.log('调用服务端获取历史排风计划成功');
					//提交成功回调
					historyScheduleList = data.rows;
					// console.log('获取历史排风计划', JSON.stringify(historyScheduleList));
					displayHistorySchedule();
				}, (error, thrown) => {
					//发生错误时，回调
					console.error('调用服务端获取历史排风计划失败', error);
				})
			}

			document.addEventListener('DOMContentLoaded', function() {
				const showMoreBtn = document.getElementById('showMoreHistory');
				if (showMoreBtn) {
					showMoreBtn.addEventListener('click', function() {
						displayHistorySchedule(true);
					});
				}
			});
		</script>
	</body>

</html>